import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { Store } from '@ngxs/store';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Navigate } from '@ngxs/router-plugin';
import { SellerSelectors } from '../../../store/seller';

@Injectable({
  providedIn: 'root',
})
export class StoreGuard implements CanActivate {

  constructor(
    private store: Store,
    private message: NzMessageService,
  ) {
  }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    const activeStoreId = this.store.selectSnapshot(SellerSelectors.activeStoreId);
    if (!activeStoreId) {
      this.message.info('请先激活一个店铺');
      this.store.dispatch(new Navigate(['/seller/store']));
      return false;
    }
    return true;
  }

}
